package com.opal.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.opal.system.service.OpalDictService;
import com.opal.system.service.impl.OpalDictServiceImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
@Configuration
@MapperScan(value = {"com.opal.**.mapper.mysql"}, sqlSessionTemplateRef  = "mysqlSqlSessionTemplate")
public class MysqlDataSource {
    //1、构建数据源
    @Bean(name = "mySqlOpalDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.opalmysql")
    public DataSource createDataSource(){
        return DataSourceBuilder.create()
                .type(ComboPooledDataSource.class)
                .build();
    }
    //2、构建sqlSessionFactory
    @Bean(name = "mysqlSqlSessionFactory")
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mySqlOpalDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        //获取xml的位置：由于我的工程就在接口类中不用配置
        //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/opal/mapper/mysql/*.xml"));//指定mapper.xml路径
        return bean.getObject();
    }

    //3、构建DataSourceTransactionManager：spring的事务管理对象
    @Bean(name = "mysqlTransactionManager")
    public DataSourceTransactionManager mysqlTransactionManager(@Qualifier("mySqlOpalDataSource") DataSource dataSource) {
        //数据源
        return new DataSourceTransactionManager(dataSource);
    }

    //4、sqlSession的实现类，不配置自动装备DefaultSqlSession
    @Bean(name = "mysqlSqlSessionTemplate")
    public SqlSessionTemplate mysqlSqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    //注入词典
    @Bean(value = "opalDicts",initMethod = "OpalDictServiceImplInit")
    public OpalDictService getOpalDictService(){
        OpalDictServiceImpl opalDictService = new OpalDictServiceImpl();
        return opalDictService;
    }

}
